package com.liuhm.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileWriter;
import com.alibaba.fastjson.JSON;
import com.liuhm.bean.Cluster;
import com.liuhm.bean.LatLng;
import com.liuhm.bean.LatLngBounds;
import com.liuhm.bean.MapResult;
import com.liuhm.entity.User;
import com.liuhm.mapper.UserMapper;
import com.liuhm.utils.AMapUtils;
import com.liuhm.utils.ClusterOverlay;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.*;

/**
 * @author liuhaomin
 * @date 2020/9/12
 */
@RequestMapping
@RestController
public class UserController {
    @Autowired
    UserMapper userMapper;
    /**
     * 获取100以内的随机数
     * @param
     * @return
     */
    private static Integer getRandomNumber_1() {
        int num=100;
        Random r = new Random();
        int d = r.nextInt(num)+1;
        System.out.println(d);
        return d ;
    }
    /**
     * 暂时没用
     * @param
     * @return
     */
    @GetMapping("/test")
    public void test() throws Exception{
        // ClassPathResource类的构造方法接收路径名称，自动去classpath路径下找文件
        ClassPathResource classPathResource = new ClassPathResource("content.json");

        // 获得File对象，当然也可以获取输入流对象
        File file = classPathResource.getFile();

        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        StringBuilder content = new StringBuilder();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line);
        }

        String content2= content.toString();
        StringBuilder stringBuilder=new StringBuilder();
        List list=JSON.parseArray(content2,Object.class);
        Integer i=0;
        for (Object data : list) {
            User user=JSON.parseObject( data.toString(),User.class);
//            stringBuilder.append("insert into user(`lnglat`) VALUES(\'"+ StringUtils.join(JSON.parseArray(user.getLnglat()),",")+"\');");
//            stringBuilder.append("\n");

            stringBuilder.append((++i)+"\t"+ JSON.parseArray(user.getLnglat()).get(0)+"\t"+JSON.parseArray(user.getLnglat()).get(1)+"\t"+ DateUtil.offset(new Date(), DateField.DAY_OF_WEEK, -getRandomNumber_1())+"\t"+DateUtil.offset(new Date(), DateField.DAY_OF_WEEK, getRandomNumber_1()));
            stringBuilder.append("\n");
            System.out.println("insert into user(`lnglat`) VALUES(\'"+ StringUtils.join(JSON.parseArray(user.getLnglat()),",")+"\');");
        }


        //data.js是文件
        FileWriter writer = new FileWriter("/user.json");
        writer.write(stringBuilder.toString());
    }
    @GetMapping("/cs")
    public void cs() throws Exception{
        List<Map<String, Object>> list=userMapper.select();
        list.forEach(data->{
            List<String> aa=new ArrayList<>();
            aa.add(data.get("lng").toString());
            aa.add(data.get("lat").toString());
            data.put("lnglat",aa);
        });
        System.out.println(JSON.toJSONString(list));
    }

    /**
     * 总共的数据
     * @return
     */
    @GetMapping("/total")
    public  Integer total() throws Exception{
        return userMapper.selectTotal();
    }
    /**
     * 方格距离算法
     * @param          bounds:map.getBounds(),
     *         mPXInMeters:   map.getResolution() 
     * @return
     */
    @PostMapping("/cs2")
    public  List<Cluster>  cs2(String bounds, double mPXInMeters, Integer zoom) throws Exception{
        List<Map<String, Object>> list=userMapper.select2();
        // 前端map.getBounds()
        LatLngBounds visibleBounds= AMapUtils.boundsToLatLngBounds(bounds);
        List<Cluster> clusters= ClusterOverlay.setClusters(list,mPXInMeters,visibleBounds,zoom,false,false);
        return clusters;
    }
    /**
     * 方格距离算法
     * @param          bounds:map.getBounds(),
     *         mPXInMeters:   map.getResolution()
     * @return 返回总数和聚合点
     */
    @PostMapping("/cs22")
    public MapResult cs22(String bounds, double mPXInMeters, Integer zoom) throws Exception{
        List<Map<String, Object>> list=userMapper.select2();
        // 前端map.getBounds()
        LatLngBounds visibleBounds= AMapUtils.boundsToLatLngBounds(bounds);
        return ClusterOverlay.setMapClusters(list,mPXInMeters,visibleBounds,zoom,false,false);
    }
    /**
     * 距离算法
     * @param          bounds:map.getBounds(),
     *         mPXInMeters:   map.getResolution()
     * @return
     */
    @PostMapping("/cs222")
    public  List<Cluster>  cs222(String bounds,double mPXInMeters,Integer zoom) throws Exception{
        List<Map<String, Object>> list=userMapper.select2();
        System.out.println(JSON.toJSONString(list));
        LatLng northeast=new LatLng(Double.parseDouble(bounds.split(";")[1].split(",")[1]),Double.parseDouble(bounds.split(";")[1].split(",")[0]));
        LatLng southwest=new LatLng(Double.parseDouble(bounds.split(";")[0].split(",")[1]),Double.parseDouble(bounds.split(";")[0].split(",")[0]));
        // 前端map.getBounds()
        LatLngBounds visibleBounds=new LatLngBounds(northeast,southwest);
        List<Cluster> clusters= ClusterOverlay.setClusters(list,mPXInMeters,visibleBounds,zoom,true,false);
        return clusters;
    }

    /**
     * 测试 距离算法  随机数据消耗的时间，看控制台
     * @param
     * @return
     */
    @GetMapping("/cs33/{len}")
    public List<Cluster> cs33(@PathVariable("len") Integer len) throws Exception{
        List<Map<String, Object>> list = new ArrayList<>();
        //随机10000个点
        for (int i = 0; i < len; i++) {
            double lat = Math.random() + 39.474923;
            double lng = Math.random() + 116.027116;
            Map<String, Object> map=new HashMap<>();
            map.put("lat",lat);
            map.put("lng",lng);
            map.put("title","title"+i);
            list.add(map);
        }
        LatLng northeast=new LatLng(40.63734763549888,120.92929604289725);
        LatLng southwest=new LatLng(30.19836691505518,115.89593346334829);
        // 前端map.getBounds()
        LatLngBounds visibleBounds=new LatLngBounds(northeast,southwest);
        double mPXInMeters=58.619102;
        Integer zoom=1;
        List<Cluster> clusters= ClusterOverlay.setOrgClusters(list,mPXInMeters,visibleBounds,zoom,true,false);
        return clusters;

    }
    @GetMapping("/cs3/{len}")
    public List<Cluster> cs3(@PathVariable("len") Integer len) throws Exception{
        List<Map<String, Object>> list = new ArrayList<>();
        //随机10000个点
        for (int i = 0; i < len; i++) {
            double lat = Math.random() + 39.474923;
            double lng = Math.random() + 116.027116;
            Map<String, Object> map=new HashMap<>();
            map.put("lat",lat);
            map.put("lng",lng);
            map.put("title","title"+i);
            list.add(map);
        }
        LatLng northeast=new LatLng(40.63734763549888,120.92929604289725);
        LatLng southwest=new LatLng(30.19836691505518,115.89593346334829);
        // 前端map.getBounds()
        LatLngBounds visibleBounds=new LatLngBounds(northeast,southwest);
        double mPXInMeters=58.619102;
        Integer zoom=1;
        List<Cluster> clusters= ClusterOverlay.setClusters(list,mPXInMeters,visibleBounds,zoom,true,false);
        return clusters;

    }
    /**
     *  测试 方格距离算法  随机数据消耗的时间，看控制台
     * @param
     * @return
     */
    @GetMapping("/cs4/{len}")
    public List<Cluster> cs4(@PathVariable("len") Integer len) throws Exception{
        List<Map<String, Object>> list = new ArrayList<>();
        //随机10000个点
        for (int i = 0; i < len; i++) {
            double lat = Math.random() + 39.474923;
            double lng = Math.random() + 116.027116;
            Map<String, Object> map=new HashMap<>();
            map.put("lat",lat);
            map.put("lng",lng);
            map.put("title","title"+i);
            list.add(map);
        }
        LatLng northeast=new LatLng(40.63734763549888,120.92929604289725);
        LatLng southwest=new LatLng(30.19836691505518,115.89593346334829);
        // 前端map.getBounds()
        LatLngBounds visibleBounds=new LatLngBounds(northeast,southwest);
        double mPXInMeters=58.619102;
        Integer zoom=1;
        List<Cluster> clusters= ClusterOverlay.setClusters(list,mPXInMeters,visibleBounds,zoom,false,false);
        return clusters;
    }




}
